<?php

namespace Bete\Http;

use Bete\Foundation\Application;
use Bete\Contract\Action as ActionContract;
use Bete\Exception\ValidationException;
use Bete\View\View;

class Action implements ActionContract
{

    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function middlewares()
    {
        return [];
    }

    public function view($view, $data = [])
    {
        return View::html($view, $data);
    }

    public function json($data, $message = 'Success', $code = 0)
    {
        $result = [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];

        echo json_encode($result);
    }

    public function renderException(\Exception $e)
    {
        if (app()->request->acceptsJson()) {
            return $this->jsonException($e);
        } else {
            return $this->viewException($e);
        }
    }

    public function jsonException(\Exception $e)
    {
        return $this->json('', $e->getMessage(), $e->getCode());
    }


    public function viewException(\Exception $e)
    {
        $data = [
            'message' => $e->getMessage(),
        ];
        $this->view('error/index', $data);
    }

}
